<?php
namespace App\Controller;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Cake\Datasource\ConnectionManager;

class EventsController extends AppController{

    public $_page_num = 30;
    public function initialize()
    {
        parent::initialize();
    }

    /*
     * create by phpstorm
     * author：Ming
     * date：2020.04.30
     * ps：导出报名信息到excel
     * */
    public function getExcel($eid = null, $pay_status = null)
    {
        $where = empty($pay_status) ? '' : ' AND event_signups.pay_status = '."'".$pay_status."' ";
        $connection = ConnectionManager::get('default');
        $sql = 'SELECT events.title as title,event_signups.id as id,event_signups.order_id as order_id,event_signups.good_id as good_id,event_signups.checked as checked,event_signups.username as name,
                event_signups.mobile as mobile,event_signups.pay_money as pay_money,event_signups.status as status,event_signups.add_time as add_time,
                event_signups.memo as memo from events,event_signups WHERE events.id = event_signups.event_id  AND events.id='.$eid.$where.' ORDER BY event_signups.id asc';
        $data = $connection->execute($sql)->fetchAll('assoc');
        if(empty($data)){
            $this->G->error("data_not_found");
            return null;
        }
        $this->loadModel('Goods');
        $goods = $this->Goods->find()
            ->select(['id','title','price'])
            ->where(['id in'=>array_column($data, 'good_id')])
            ->toArray();
        if(empty($goods)){
            $this->G->error("ticket_error");
            return null;
        }
        $arr = [];
        $brr = [];
        $crr = [];
        foreach ($goods as $key1=>$value1){
            $arr[$value1['id']] = ['title'=>$value1['title'],'price'=>$value1['price']];
        }
        $flag = 0;
        $this->loadModel('Orders');
        $this->loadComponent('UserCache');
        foreach ($data as $key=>$value){
            $title = $value['title'];
            $list = [];
            $orders = $this->Orders->findById($value["order_id"])->first();
            if(empty($orders)){
                $this->G->error("order_error");
                return null;
            }
            $users = $this->UserCache->getVal($orders['drawee_id']);
            $user_infos = $this->UserCache->getVal($orders['drawee_id'], null, 'UserInfos');
            $list['nickname'] = empty($user_infos) ? '' : $user_infos['nickname'];
            $list['mobile_user'] = empty($users['mobile']) ? '' : $users['mobile'];
            $list['alias'] = $arr[$value['good_id']]['title'];
            $list['price'] = $arr[$value['good_id']]['price']/100;
            $list['pay_money'] = $value['pay_money']/100;
            $list['pay_from'] = $orders['pay_from'];
            if($value['status'] == 'nopay'){
                $list['status'] = '待支付';
            }elseif ($value['status'] == 'wait'){
                $list['status'] = '待参与';
            }elseif ($value['status'] == 'finish'){
                $list['status'] = '已完成';
            }elseif ($value['status'] == 'refund'){
                $list['status'] = '退款';
            }elseif ($value['status'] == 'close'){
                $list['status'] = '交易关闭';
            }elseif ($value['status'] == 'cancel'){
                $list['status'] = '已取消';
            }
            $list['name'] = $value['name'];
            $list['id'] = $value['id'];
            $list['mobile'] = $value['mobile'];
            $list['checked'] = $value['checked'] == 0 ? '未验票' : '已验票';
            $list['add_time'] = date('Y-m-d H:i:s',$value['add_time']);
            $memo = json_decode($value['memo'], true);
            if(!empty($memo)){
                foreach ($memo as $k=>$v){
                    if($flag == 0){
                        $brr[] =  $v['name'];
                    }
                    $list['value'.$k] = $v['value'];
                }
            }
            $crr[] = $list;
            $flag = 1;
        }
        $spreadsheet = new Spreadsheet();
        $spreadsheet->getProperties()->setCreator("Sponsor")
            ->setLastModifiedBy("Sponsor")
            ->setTitle("Users of event")
            ->setSubject("Users")
            ->setDescription("Users of event which you choose")
            ->setKeywords("Users")
            ->setCategory("Users of event");
        $spreadsheet->setActiveSheetIndex(0);
        $spreadsheet->getActiveSheet()->setTitle('报名列表');
        $spreadsheet->getActiveSheet()->getRowDimension('1')->setRowHeight(25); //首行高度
        // 设置表格宽度
        $spreadsheet->getActiveSheet()->getColumnDimension('A')->setWidth(10);
        $spreadsheet->getActiveSheet()->getColumnDimension('B')->setWidth(10);
        $spreadsheet->getActiveSheet()->getColumnDimension('C')->setWidth(25);
        $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(25);
        $spreadsheet->getActiveSheet()->getColumnDimension('E')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('G')->setWidth(15);
        $spreadsheet->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('I')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('J')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('K')->setWidth(40);
        $spreadsheet->getActiveSheet()->getColumnDimension('L')->setWidth(10);
        $arr1 = ['M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD'];
        $flag1 = $arr1[0].'1';
        if(!empty($brr)){
            for($i=0;$i<count($brr);$i++){
                $spreadsheet->getActiveSheet()->getColumnDimension($arr1[$i])->setWidth(40);
                $flag1 = $arr1[$i].'1';
            }
        }
        // 列名表头文字加粗
        $spreadsheet->getActiveSheet()->getStyle('A1:'.$flag1)->getFont()->setBold(true);
        // 列表头文字居中
        $spreadsheet->getActiveSheet()->getStyle('A1:'.$flag1)->getAlignment()
            ->setHorizontal(Alignment::HORIZONTAL_CENTER);
        // 列名赋值
        $spreadsheet->getActiveSheet()->setCellValue('A1', '报名ID');
        $spreadsheet->getActiveSheet()->setCellValue('B1', '昵称');
        $spreadsheet->getActiveSheet()->setCellValue('C1', '用户手机');
        $spreadsheet->getActiveSheet()->setCellValue('D1', '票种');
        $spreadsheet->getActiveSheet()->setCellValue('E1', '门票单价');
        $spreadsheet->getActiveSheet()->setCellValue('F1', '实际支付');
        $spreadsheet->getActiveSheet()->setCellValue('G1', '参与状态');
        $spreadsheet->getActiveSheet()->setCellValue('H1', '姓名');
        $spreadsheet->getActiveSheet()->setCellValue('I1', '联系电话');
        $spreadsheet->getActiveSheet()->setCellValue('J1', '是否验票');
        $spreadsheet->getActiveSheet()->setCellValue('K1', '报名时间');
        $spreadsheet->getActiveSheet()->setCellValue('L1', '支付方式');
        if(!empty($brr)){
            for($i=0;$i<count($brr);$i++){
                $spreadsheet->getActiveSheet()->setCellValue($arr1[$i].'1', $brr[$i]);
            }
        }
        // 数据起始行
        $row_num = 2;
        // 向每行单元格插入数据
        foreach($crr as $value)
        {
            // 设置所有垂直居中
            $spreadsheet->getActiveSheet()->getStyle('A' . $row_num. ':' .$flag1 . $row_num)->getAlignment()
                ->setHorizontal(Alignment::HORIZONTAL_CENTER);
            // 设置价格为数字格式
            $spreadsheet->getActiveSheet()->getStyle('E' . $row_num. ':' .'F' . $row_num )->getNumberFormat()
                ->setFormatCode(NumberFormat::FORMAT_NUMBER_00);
            // 设置单元格数值
            $spreadsheet->getActiveSheet()->setCellValue('A' . $row_num, $value['id']);
            $spreadsheet->getActiveSheet()->setCellValue('B' . $row_num, $value['nickname']);
            $spreadsheet->getActiveSheet()->setCellValue('C' . $row_num, $value['mobile_user']);
            $spreadsheet->getActiveSheet()->setCellValue('D' . $row_num, $value['alias']);
            $spreadsheet->getActiveSheet()->setCellValue('E' . $row_num, $value['price']);
            $spreadsheet->getActiveSheet()->setCellValue('F' . $row_num, $value['pay_money']);
            $spreadsheet->getActiveSheet()->setCellValue('G' . $row_num, $value['status']);
            $spreadsheet->getActiveSheet()->setCellValue('H' . $row_num, $value['name']);
            $spreadsheet->getActiveSheet()->setCellValue('I' . $row_num, $value['mobile']);
            $spreadsheet->getActiveSheet()->setCellValue('J' . $row_num, $value['checked']);
            $spreadsheet->getActiveSheet()->setCellValue('K' . $row_num, $value['add_time']);
            $spreadsheet->getActiveSheet()->setCellValue('L' . $row_num, $value['pay_from']);
            if(!empty($brr)){
                for($i=0;$i<count($brr);$i++){
                    if(empty($value['value'.$i])){
                        $value['value'.$i] = '';
                    }
                    if(is_array($value['value'.$i])){
                        if(empty($value['value'.$i][0])){
                            $str = '';
                        }else{
                            $str = implode(' ', $value['value'.$i]);
                        }
                        $spreadsheet->getActiveSheet()->setCellValue($arr1[$i].$row_num, $str);
                    }else{
                        $spreadsheet->getActiveSheet()->setCellValue($arr1[$i].$row_num, $value['value'.$i]);
                    }
                }
            }
            $row_num++;
        }
        $objWriter = IOFactory::createWriter($spreadsheet, 'Xls');
        $outputFileName = mb_substr($title,0,10).'活动名单_'.date('Ymdhis').'.xls';
        //输出到浏览器
        ob_end_clean();
        header('Content-Type: application/vnd.oasis.opendocument.spreadsheet');
        header('Content-Disposition: attachment;filename="'.$outputFileName.'"');
        header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0
        $objWriter->save('php://output');
        exit;
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：获取活动报名内容
   * */
    public function getSignup()
    {
        $event_id = $this->request->getData('event_id');
        $this->loadModel('Textareas');
        $textarea = $this->Textareas->find()
            ->select(['content'])
            ->where(['content_type'=>'event_signups','content_id'=>$event_id])
            ->first();
        $textarea = empty($textarea) ? '' : json_decode($textarea['content']);
        $this->G->success('Success',['content'=>$textarea]);
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：修改活动报名内容
   * */
    public function updateSignup()
    {
        $event_id = $this->request->getData('event_id');
        $content = $this->request->getData('content');
        $this->loadModel('Textareas');
        $textarea = $this->Textareas->find()
            ->select(['id'])
            ->where(['content_type'=>'event_signups','content_id'=>$event_id])
            ->first();
        if(empty($textarea)){
            $textarea = $this->Textareas->newEntity();
            $textarea->content_type = 'event_signups';
            $textarea->content_id = $event_id;
            $textarea->content = json_encode($content);
            $this->Textareas->save($textarea);
        }else{
            $this->Textareas->query()
                ->update()
                ->set(['content'=>json_encode($content)])
                ->where(['id' => $textarea['id']])
                ->execute();
            $this->loadComponent('TextareaCache');
            $this->TextareaCache->deleteCache('event_signups', $event_id);
        }
        $this->G->success('Success');
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：新增活动报名内容
   * */
    public function addSignup()
    {
        $event_id = $this->request->getData('event_id');
        $content = $this->request->getData('content');
        $this->loadModel('Textareas');
        $textarea = $this->Textareas->newEntity();
        $textarea->content_type = 'event_signups';
        $textarea->content_id = $event_id;
        $textarea->content = json_encode($content);
        $this->Textareas->save($textarea);
        $this->G->success('Success');
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：获取活动的报名人
   * */
    public function getSignups()
    {
        $pay_status = $this->request->getData('pay_status');
        $event_id = $this->request->getData('event_id');
        $mobile = $this->request->getData('mobile');
        $page = $this->request->getData('page');
        $where = [];
        $where['event_id'] = $event_id;
        if(!empty($pay_status)){
            $where['pay_status'] = $pay_status;
        }
        if(!empty($mobile)){
            $where['mobile'] = $mobile;
        }
        $page = empty($page) ? 1 : $page;
        $this->loadModel('EventSignups');
        $event_signups = $this->EventSignups->find()
            ->where($where)
            ->order(['id asc'])
            ->limit($this->_page_num)
            ->page($page);
        $data = [];
        $data['pageTotal'] = ceil($event_signups->count()/$this->_page_num);
        $data['list'] = [];
        $event_signups = $event_signups->toArray();
        if(!empty($event_signups)){
            $this->loadModel('Orders');
            foreach ($event_signups as $k=>$v){
                $order = $this->Orders->findById($v['order_id'])->first();
                if(empty($order)){
                    continue;
                }
                $event_signups[$k]['order_no'] = $order['order_no'];
                $event_signups[$k]['pay_money'] = $v['pay_money']/100;
                $event_signups[$k]['checked_time'] = empty($v['checked_time']) ? '' : date('Y-m-d H:i:s', $v['checked_time']);
                $event_signups[$k]['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
                $data['list'][] = $event_signups[$k];
            }
        }
        $this->G->success('Success', $data);
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：设置活动门票
   * */
    public function setTickets()
    {
        $data = $this->request->getData();
        if(!is_numeric($data['event_id'])){
            $this->G->error("event_id_error");
            return null;
        }
        if(empty(trim($data['title']))){
            $this->G->error("title_error");
            return null;
        }
        $this->loadComponent('EventCache');
        $event = $this->EventCache->getVal($data['event_id']);
        if(empty($event)){
            $this->G->error("event_error");
            return null;
        }
        $this->loadModel('Goods');
        $good = $this->Goods->newEntity();
        $good->memo = $data['title'];
        $good->title = $data['title'];
        $good->user_group = $data['user_group'];
        $good->max_buy = $data['max_buy'];
        $good->min_buy = $data['min_buy'];
        $good->pre_num = $data['pre_num'];
        $good->img = $this->G->setImgUrl($data['img']);
        $good->price = $data['price']*100;
        $good->status = $data['status'];
        $good_save = $this->Goods->save($good);
        if($good_save){
            $this->loadModel('GoodsContents');
            $good_content = $this->GoodsContents->newEntity();
            $good_content->good_id = $good_save->id;
            $good_content->content_type = 'events';
            $good_content->content_id = $data['event_id'];
            $this->GoodsContents->save($good_content);
            $this->loadModel('GoodsInstocks');
            $good_instock = $this->GoodsInstocks->newEntity();
            $good_instock->good_id = $good_save->id;
            $good_instock->price = $data['price']*100;
            $good_instock->num = $data['in_stock'];
            $good_instock->add_time = time();
            $this->GoodsInstocks->save($good_instock);
            if(!empty($data['deal_id'])){
                $this->loadModel('DealGoods');
                $deal_good = $this->DealGoods->newEntity();
                $deal_good->deal_type = 'deal_points';
                $deal_good->deal_id = $data['deal_id'];
                $deal_good->good_id = $good_save->id;
                $this->DealGoods->save($deal_good);
                $this->loadComponent('DealGoodCache');
                $this->DealGoodCache->deleteCache($good_save->id);
            }
        }
        $this->loadComponent('GoodCache');
        $this->GoodCache->deleteList('events', $data['event_id']);
        $this->loadComponent('InStockCache');
        $this->InStockCache->deleteCache($good_save->id);
        $this->G->success('Success');
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：获取活动门票
   * */
    public function getTickets()
    {
        $event_id = $this->request->getData('event_id');
        if(!is_numeric($event_id)){
            $this->G->error("event_id_error");
            return null;
        }
        $this->loadModel('GoodsContents');
        $good_ids = $this->GoodsContents->find()
            ->select(['good_id'])
            ->where(['content_type'=>'events','content_id'=>$event_id])
            ->toArray();
        if(empty($good_ids)){
            $this->G->success('Success', []);
            return null;
        }
        $this->loadComponent('GoodCache');
        $this->loadComponent('InStockCache');
        $this->loadComponent('OutStockCache');
        $data = [];
        foreach ($good_ids as $k=>$v){
            $good = $this->GoodCache->getVal($v['good_id']);
            if(empty($good)){
                continue;
            }
            $in_stock = $this->InStockCache->getVal($v['good_id']);
            $out_stock = $this->OutStockCache->getVal($v['good_id']);
            $good['img'] = empty($good['img']) ? '' : $this->G->getImgUrl($good['img']);
            $good['in_stock'] = empty($in_stock) ? 0 : $in_stock;
            $good['out_stock'] = empty($out_stock) ? 0 : $out_stock;
            $data[] = $good;
        }
        $this->G->success('Success', $data);
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：修改活动门票
   * */
    public function updateTickets()
    {
        $data = $this->request->getData();
        if(!is_numeric($data['id'])){
            $this->G->error("id_error");
            return null;
        }
        if(empty(trim($data['title']))){
            $this->G->error("title_error");
            return null;
        }
        $this->loadModel('Goods');
        $goods = $this->Goods->findById($data['id'])->select(['id'])->first();
        if(empty($goods)){
            $this->G->error("id_error");
            return null;
        }
        $good = $this->Goods->newEntity();
        $good->id = $data['id'];
        $good->memo = $data['title'];
        $good->user_group = $data['user_group'];
        $good->title = $data['title'];
        $good->max_buy = $data['max_buy'];
        $good->min_buy = $data['min_buy'];
        $good->pre_num = $data['pre_num'];
        $good->img = $this->G->setImgUrl($data['img']);
        $good->price = $data['price']*100;
        $good->status = $data['status'];
        $this->Goods->save($good);
        $this->loadModel('GoodsInstocks');
        $this->GoodsInstocks->query()
            ->update()
            ->set(['price'=>$data['price'],'num'=>$data['in_stock']])
            ->where(['good_id' => $data['id']])
            ->execute();
        $this->loadModel('DealGoods');
        $deal_goods = $this->DealGoods->findByGoodId($data['id'])->first();
        if(empty($deal_goods) && !empty($data['deal_id'])){
            $deal_good = $this->DealGoods->newEntity();
            $deal_good->deal_type = 'deal_points';
            $deal_good->deal_id = $data['deal_id'];
            $deal_good->good_id = $data['id'];
            $this->DealGoods->save($deal_good);
            $this->loadComponent('DealGoodCache');
            $this->DealGoodCache->deleteCache($data['id']);
        }elseif (!empty($deal_goods) && empty($data['deal_id'])){
            $this->DealGoods->deleteAll(['id'=>$deal_goods['id']]);
            $this->loadComponent('DealGoodCache');
            $this->DealGoodCache->deleteCache($data['id']);
        }elseif(!empty($deal_goods) && !empty($data['deal_id'])){
            $this->DealGoods->query()
                ->update()
                ->set(['deal_id'=>$data['deal_id']])
                ->where(['id' => $deal_goods['id']])
                ->execute();
            $this->loadComponent('DealGoodCache');
            $this->DealGoodCache->deleteCache($data['id']);
        }
        $this->loadComponent('GoodCache');
        $this->GoodCache->deleteCache($data['id']);
        $this->loadComponent('InStockCache');
        $this->InStockCache->deleteCache($data['id']);
        $this->G->success('Success');
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：活动列表
   * */
    public function getList()
    {
        $data = $this->request->getData();
        $where = [];
        if(isset($data['enabled']) && is_numeric($data['enabled'])){
            $where['enabled'] = $data['enabled'];
        }
        if(!empty($data['status'])){
            $where['status in'] = $data['status'];
        }
        $page = empty($data['page']) ? 1 :$data['page'];
        if(!empty($data['title'])){
            $where['title like'] = '%'.$data['title'].'%';
        }
        $live = $this->Events->find()
            ->where($where)
            ->limit($this->_page_num)
            ->page($page);
        $result = [];
        $result['pageTotal'] = ceil($live->count()/$this->_page_num);
        $result['list'] = [];
        $live = $live->toArray();
        if(!empty($live)){
            foreach ($live as $k=>$v){
                $live[$k]['start_time'] = date('Y-m-d H:i:s', $v['start_time']);
                $live[$k]['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
                $result['list'][] = $live[$k];
            }
        }
        $this->G->success('Success', $result);
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：新增活动
   * */
    public function add()
    {
        $title = $this->request->getData("title");
        $poster = $this->request->getData("poster");
        $content = $this->request->getData("content");
        $province = $this->request->getData("province");
        $city = $this->request->getData("city");
        $address = $this->request->getData("address");
        $start_time = $this->request->getData("start_time");
        $end_time = $this->request->getData("end_time");
        $sell_start = $this->request->getData("sell_start");
        $sell_end = $this->request->getData("sell_end");
        $low_price = $this->request->getData("low_price");
        $status = $this->request->getData("status");
        $enabled = $this->request->getData("enabled");
        $view_group = $this->request->getData("view_group");
        $is_show = $this->request->getData("is_show");
        $data = $this->request->getData();
        if(empty($data)){
            $this->G->error("data_error");
            return null;
        }
        foreach ($data as $k=>$v){
            if($k === 'enabled' && !is_numeric($v)){
                $this->G->error("enabled_error");
                return null;
            }else{
                continue;
            }
            if($k === 'is_show' && !is_numeric($v)){
                $this->G->error("is_show_error");
                return null;
            }else{
                continue;
            }
            if(empty($v)){
                $this->G->error($k."_error");
                return null;
            }
        }
        $event = $this->Events->newEntity();
        $event->title = $title;
        $event->poster = $poster;
        $event->province = $province;
        $event->city = $city;
        $event->address = $address;
        $event->start_time = strtotime($start_time);
        $event->end_time = strtotime($end_time);
        $event->sell_start = strtotime($sell_start);
        $event->sell_end = strtotime($sell_end);
        $event->low_price = $low_price*100;
        $event->add_time = time();
        $event->status = $status;
        $event->enabled = $enabled;
        $event->is_show = $is_show;
        $event->view_group = $view_group;
        $event_save = $this->Events->save($event);
        $this->loadComponent('TextareaCache');
        $this->loadComponent('ContentFormat');
        $content  = $this->ContentFormat->clean($content)[0];
        $this->TextareaCache->add('events', $event_save->id, $content);
        $this->loadComponent('EventCache');
        $this->EventCache->deleteList();
        $this->G->success('Success');
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：新增活动
   * */
    public function update()
    {
        $id = $this->request->getData("id");
        $title = $this->request->getData("title");
        $poster = $this->request->getData("poster");
        $content = $this->request->getData("content");
        $province = $this->request->getData("province");
        $city = $this->request->getData("city");
        $address = $this->request->getData("address");
        $start_time = $this->request->getData("start_time");
        $end_time = $this->request->getData("end_time");
        $sell_start = $this->request->getData("sell_start");
        $sell_end = $this->request->getData("sell_end");
        $low_price = $this->request->getData("low_price");
        $status = $this->request->getData("status");
        $enabled = $this->request->getData("enabled");
        $view_group = $this->request->getData("view_group");
        $is_show = $this->request->getData("is_show");
        $data = $this->request->getData();
        if(empty($data)){
            $this->G->error("data_error");
            return null;
        }
        if(!is_numeric($id)){
            $this->G->error("id_error");
            return null;
        }
        foreach ($data as $k=>$v){
            if($k === 'enabled' && !is_numeric($v)){
                $this->G->error("enabled_error");
                return null;
            }else{
                continue;
            }
            if($k === 'is_show' && !is_numeric($v)){
                $this->G->error("is_show_error");
                return null;
            }else{
                continue;
            }
            if(empty($v)){
                $this->G->error($k."_error");
                return null;
            }
        }
        $events = $this->Events->findById($id)->select(['id'])->first();
        if(empty($events)){
            $this->G->error("event_error");
            return null;
        }
        $event = $this->Events->newEntity();
        $event->id = $id;
        $event->title = $title;
        $event->poster = $poster;
        $event->province = $province;
        $event->city = $city;
        $event->address = $address;
        $event->start_time = strtotime($start_time);
        $event->end_time = strtotime($end_time);
        $event->sell_start = strtotime($sell_start);
        $event->sell_end = strtotime($sell_end);
        $event->low_price = $low_price*100;
        $event->status = $status;
        $event->enabled = $enabled;
        $event->is_show = $is_show;
        $event->view_group = $view_group;
        $this->Events->save($event);
        $this->loadComponent('TextareaCache');
        $this->loadComponent('ContentFormat');
        $content  = $this->ContentFormat->clean($content)[0];
        $this->TextareaCache->update('events', $id, $content);
        $this->loadComponent('EventCache');
        $this->EventCache->deleteCache($id);
        $this->EventCache->deleteList();
        $this->G->success('Success');
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：删除活动
   * */
    public function delete()
    {
        if(!$this->request->is("post")){
            $this->G->error("post_error");
            return null;
        }
        $ids = $this->request->getData("ids");
        if(empty($ids) || !is_array($ids)){
            $this->G->error("ids_error");
            return null;
        }
        $this->loadComponent('EventCache');
        $this->EventCache->deleteList();
        $this->Events->deleteAll(['id in'=>$ids]);
        $this->G->success("Success");
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：获取指定的活动
   * */
    public function getInfo()
    {
        $id = $this->request->getData("id");
        if(!is_numeric($id)){
            $this->G->error("id_error");
            return null;
        }
        $events = $this->Events->findById($id)->first();
        if(empty($events)){
            $this->G->error("event_error");
            return null;
        }
        $events['start_time'] = date('Y-m-d H:i:s', $events['start_time']);
        $events['sell_end'] = date('Y-m-d H:i:s', $events['sell_end']);
        $events['sell_start'] = date('Y-m-d H:i:s', $events['sell_start']);
        $events['end_time'] = date('Y-m-d H:i:s', $events['end_time']);
        $events['add_time'] = date('Y-m-d H:i:s', $events['add_time']);
        $this->loadComponent('TextareaCache');
        $textarea = $this->TextareaCache->getVal('events', $id);
        $this->loadComponent('ContentFormat');
        $events['content']  = empty($textarea) ? '' : $this->ContentFormat->add($textarea['content']);
        $this->G->success("Success", $events);
    }

}
?>